package com.wusuowei.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wusuowei.springboot.constant.Constants;
import com.wusuowei.springboot.exception.ServiceException;
import com.wusuowei.springboot.mapper.UserMapper;
import com.wusuowei.springboot.model.dto.UserDTO;
import com.wusuowei.springboot.model.dto.UserPasswordDTO;
import com.wusuowei.springboot.model.po.Menu;
import com.wusuowei.springboot.model.po.User;
import com.wusuowei.springboot.model.po.UserRole;
import com.wusuowei.springboot.service.MenuService;
import com.wusuowei.springboot.service.UserService;
import com.wusuowei.springboot.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lgy
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleServiceImpl userRoleService;

    @Autowired
    private RoleServiceImpl roleService;

    @Override
    public UserDTO login(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if (one != null) {
            BeanUtil.copyProperties(one, userDTO, true);
            List<Menu> userMenus = menuService.getUserMenus(one.getId());
            String roles = getRoles(one.getId());
            userDTO.setRole(roles);
            userDTO.setMenus(userMenus);
            // 设置token
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            userDTO.setToken(token);
            return userDTO;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }
    }





    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        int update = userMapper.updatePassword(userPasswordDTO);
        if (update < 1) {
            throw new ServiceException(Constants.CODE_600, "密码错误");
        }
    }

    @Override
    public User register(UserDTO userDTO) {
        userDTO.setPassword(SecureUtil.md5(userDTO.getPassword()));
        User one = getUserInfo(userDTO);
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(userDTO, one, true);
            save(one);  // 把 copy完之后的用户对象存储到数据库
            //设置默认角色
            UserRole userRole = new UserRole();
            userRole.setRoleId(2L);
            userRole.setUserId(one.getId());
            userRoleService.save(userRole);

        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }


    @Override
    public Page<User> findPage(Page<User> page, String username, String email, String address) {
        return userMapper.findPage(page, username, email, address);
    }

    @Override
    public User getByName(String username) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        String roles = getRoles(user.getId());
        user.setRole(roles);
        return user;
    }

    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", SecureUtil.md5(userDTO.getPassword()));
        User one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }
    private String getRoles(Long uid) {
        Long id = userRoleService.getOne(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, uid)).getRoleId();
        return id.toString();
    }
}
